﻿namespace CatClient.Util
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Sockets;
    using System.Runtime.CompilerServices;

    public class NetworkInterfaceManager
    {
        private static IPHostEntry _host;
        private static object _lock = new object();

        public static byte[] GetAddressBytes()
        {
            using (IEnumerator<IPAddress> enumerator = (from ip in GetHost().AddressList
                                                        where ip.AddressFamily == AddressFamily.InterNetwork
                                                        select ip).GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    return enumerator.Current.GetAddressBytes();
                }
            }
            throw new NotSupportedException("No IP address found");
        }

        private static IPHostEntry GetHost()
        {
            if (_host != null)
            {
                return _host;
            }
            object obj2 = _lock;
            lock (obj2)
            {
                _host = Dns.GetHostEntry(GetLocalHostName());
                return _host;
            }
        }

        public static string GetLocalHostAddress()
        {
            using (IEnumerator<IPAddress> enumerator = (from ip in GetHost().AddressList
                                                        where ip.AddressFamily == AddressFamily.InterNetwork
                                                        select ip).GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    return enumerator.Current.ToString();
                }
            }
            throw new NotSupportedException("No IP address found");
        }

        public static string GetLocalHostName() => Dns.GetHostName();
    }
}

